package online.yysh.charging;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.google.gson.Gson;
import com.google.zxing.Result;

import online.yysh.charging.base.BaseActivity;
import online.yysh.charging.bean.request.PortIsAvailableRequest;
import online.yysh.charging.bean.response.GetPortAvailableResponse;
import online.yysh.charging.utils.HttpUtil;
import online.yysh.charging.zxing.BeepManager;
import online.yysh.charging.zxing.CameraManager;
import online.yysh.charging.utils.Constant;
import online.yysh.charging.zxing.InactivityTimer;
import online.yysh.charging.zxing.ScanAndChargeActivityHandler;
import online.yysh.charging.zxing.ViewfinderView;
import online.yysh.charging.zxing.ZxingConfig;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 扫码充电Activity
 */
public class ScanAndChargeActivity extends BaseActivity implements View.OnClickListener, SurfaceHolder.Callback {

    private ImageView iv_inputNumber, iv_openLight;
    private TextView tv_light;

    public ZxingConfig config;
    private SurfaceView previewView;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private CameraManager cameraManager;
    private ScanAndChargeActivityHandler handler;
    private SurfaceHolder surfaceHolder;

    private String cameraPermission = Manifest.permission.CAMERA;
    private final int CAMERA_REQUEST_CODE = 300;

    //是否第一次初始化摄像头
    private boolean isFirstInit;
    private SharedPreferences sp;
    private boolean flashStatus;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_and_charge;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_light = findViewById(R.id.tv_light);
        iv_inputNumber = findViewById(R.id.iv_number);
        iv_inputNumber.setOnClickListener(this);
        iv_openLight = findViewById(R.id.iv_light);
        iv_openLight.setOnClickListener(this);

        previewView = findViewById(R.id.preview_view);
        previewView.setOnClickListener(this);
        viewfinderView = findViewById(R.id.viewfinder_view);

        config = new ZxingConfig();
        config.setFullScreenScan(false);
        viewfinderView.setZxingConfig(config);

        beepManager = new BeepManager(this);
        inactivityTimer = new InactivityTimer(this);

    }

    public void initCamera() {

        cameraManager = new CameraManager(getApplication(), config);

        viewfinderView.setCameraManager(cameraManager);
        handler = null;

        surfaceHolder = previewView.getHolder();

        if (isFirstInit) {
            initCamera(surfaceHolder);
            isFirstInit = false;
            sp.edit().putBoolean(Constant.SP_KEY_IS_FIRST_INIT, isFirstInit).commit();
        } else {
            if (hasSurface) {
                initCamera(surfaceHolder);
            } else {
                // 重置callback，等待surfaceCreated()来初始化camera
                surfaceHolder.addCallback(this);
            }
        }

        beepManager.updatePrefs();
        inactivityTimer.onResume();
    }

    /**
     * 申请摄像头权限
     */
    public void requestPermission() {
        //申请摄像头权限
        if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, cameraPermission)) {
            logE("已有权限");
            initCamera();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{cameraPermission}, CAMERA_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //授权通过
                logE("申请通过");
            } else {
                //授权失败
                Toast.makeText(this, R.string.prompt_camera_permission, Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestPermission();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        if (cameraManager != null) {
            cameraManager.closeDriver();
        }
        if (!hasSurface && surfaceHolder != null) {
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    /**
     * 获取到二维码信息
     *
     * @param rawResult
     */
    public void handleDecode(Result rawResult) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();

        String data = rawResult.getText();
        logD("扫描到的结果是:" + data);

        if (data.contains("www.sinoicar.com/GXMiniApp/Api/WX/")) {
            //说明是扫描到的充电桩码
            String[] dataArray = data.substring(data.lastIndexOf("/") + 1).split("-");
            portIsAvailable(dataArray[0], dataArray[1]);
        }
    }

    /**
     * 判断桩号是否可用
     *
     * @param port
     * @param deviceId
     */
    private void portIsAvailable(final String port, final String deviceId) {
        int portInt = 66;
        if ("A".equals(port)) {
            portInt = 65;
        }
        PortIsAvailableRequest request = new PortIsAvailableRequest(openid, deviceId, portInt);
        HttpUtil.getInstance().isAvailable(request, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                logE("result:" + result);
                GetPortAvailableResponse getPortAvailableResponse = new Gson().fromJson(result, GetPortAvailableResponse.class);
                if ("ok".equals(getPortAvailableResponse.getStatus())) { //可用
                    Intent intent = new Intent(ScanAndChargeActivity.this, SelectChargingModeActivity.class);
                    intent.putExtra("chargingData", deviceId + "_" + port);
                    startActivity(intent);
                    finish();
                } else {
                    //桩不可用
                    final String data = getPortAvailableResponse.getData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast(data);
                        }
                    });
                    finish();
                }
            }
        });
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new ScanAndChargeActivityHandler(this, cameraManager);
            }
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
//            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            Log.w(TAG, "Unexpected error initializing camera", e);
//            displayFrameworkBugMessageAndExit();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        logE("surfaceCreated");
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        logE("surfaceDestroyed");
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }


    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    protected void initData() {
        sp = getSharedPreferences(Constant.SP_NAME, MODE_PRIVATE);
        isFirstInit = sp.getBoolean(Constant.SP_KEY_IS_FIRST_INIT, true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_light:
                cameraManager.switchFlashLight(handler);
                if (flashStatus) {
                    flashStatus = false;
                    iv_openLight.setBackgroundResource(R.mipmap.flashlight_off);
                    tv_light.setText(R.string.click_open_light);
                } else {
                    flashStatus = true;
                    iv_openLight.setBackgroundResource(R.mipmap.falshlight_on);
                    tv_light.setText(R.string.click_close_light);
                }
                break;
            case R.id.iv_number:
                startActivity(new Intent(ScanAndChargeActivity.this, InputDeviceNumberActivity.class));
                finish();
                break;
            default:
                break;
        }
    }

}